package com.lottery.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lottery.server.common.JsonResult;
import com.lottery.server.entity.Account;
import com.lottery.server.mapper.AccountMapper;
import com.lottery.server.util.JwtUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/lottery/admin")
public class AuthController {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private JwtUtil jwtUtil;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @PostMapping("/login")
    public JsonResult<String> login(@RequestBody LoginRequest request) {
        Account account = accountMapper.selectOne(
            new LambdaQueryWrapper<Account>()
                .eq(Account::getUsername, request.getUsername())
        );

        String encode = passwordEncoder.encode("123456");

        if (account == null || !passwordEncoder.matches(request.getPassword(), account.getPassword())) {
            return JsonResult.error("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(account.getUsername());
        return JsonResult.success(token);
    }

    @Data
    public static class LoginRequest {
        private String username;
        private String password;
    }
} 